package com.books4sale.feed;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.restlet.data.MediaType;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.books4sale.admin.dto.Book;
import com.books4sale.admin.dto.tools.PMF;

public class BooksByCollage extends ServerResource {

	@Get("xml")
	public Representation BooksByCollage(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Book> results = (List<Book>) pm.newQuery(Book.class).execute();
		ArrayList<String> temp = new ArrayList<String>();
		DomRepresentation representation = null;
		try {
			representation = new DomRepresentation(
					MediaType.TEXT_XML);
			Document doc = representation.getDocument();
			Element rootElement = doc.createElement("books");
			for (Book book : results) {
				if(!temp.contains(book.getBookCollage())){
					temp.add(book.getBookCollage());
					Element collage = doc.createElement("collage");
					collage.setAttribute("name", book.getBookCollage());
					
					for (Book bookItem : results) {
						if(bookItem.getBookCollage().equals(book.getBookCollage())){
							Element bookXMLNode = doc.createElement("book");
							Element bookShopInfo = doc.createElement("shop");
							
							// book info
							bookXMLNode.setAttribute("name", bookItem.getBookName());
							bookXMLNode.setAttribute("subject", bookItem.getBookSubject());
							bookXMLNode.setAttribute("price", bookItem.getBookPrice());
							bookXMLNode.setAttribute("date", bookItem.getDate().toString());
							
							// shop info
							bookShopInfo.setAttribute("shopName", bookItem.getProfile().getShopName());
							bookShopInfo.setAttribute("shopAddress", bookItem.getProfile().getShopAddress());
							bookShopInfo.setAttribute("shopCity", bookItem.getProfile().getShopCity());
							bookShopInfo.setAttribute("shopPhone", bookItem.getProfile().getShopPhone());
							bookXMLNode.appendChild(bookShopInfo);
							collage.appendChild(bookXMLNode);
						}
					}
					rootElement.appendChild(collage);
				}
			}
			doc.appendChild(rootElement);
			doc.normalizeDocument();
		}catch (Exception e) {
			// TODO: handle exception
		}

		return representation;
	}
}
